package org.datamining.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

public class PropertyFileLoader {

	private HashMap<String, String> dictionary = (HashMap<String, String>)new HashMap<String, String>();
	
	/**
	 * Ana olusturucu property dosyasi yukleyiciyi harekete gecirir
	 * 
	 * @param propertyFileName: doldurulacak olan property dosyanizin classpath'e gore yolunu
	 * ve ismini yazin "abc.properties" yada "property-files/abc.properties" gibi.
	 */
	public PropertyFileLoader(String propertyFileName){
		LoadPropertyFile(propertyFileName);
	}

	/**
	 * Property dosyasini okuyarak dictionary'de saklar. get metotlari uzerinden 
	 * bu degerleri okumamizi saglar.
	 * 
	 * @param fileName: doldurulacak olan property dosyanizin classpath'e gore yolunu
	 * ve ismini yazin "abc.properties" yada "property-files/abc.properties" gibi.
	 */
	private void LoadPropertyFile(String fileName) {
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			String classPathURL = PropertyFileLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
			String classPath = new java.net.URI(classPathURL).getPath();
			fis = new FileInputStream(classPath + File.separator + fileName);
	        InputStreamReader isr = new InputStreamReader(fis, "UTF8");
			// load a properties file
			prop.load(isr);

			Enumeration<Object> enumeration = prop.keys();

			while (enumeration.hasMoreElements()) {
				String key = (String) enumeration.nextElement();
				dictionary.put(key, prop.getProperty(key));
			}

		}
		catch (URISyntaxException ex)
		{
			ex.printStackTrace();
		}
		catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
	
	//Dictionary de�i�kenindeki bir anahtara bakarak ona ait de�erini d�nd�r�r, yoksa ayn�s�n� d�nd�r�r
	public String getSubstitution(String key)
	{
		//key sozlukte varsa, keyin anahtarini getir, yoksa aynisini teslim et.
		return dictionary.containsKey(key) ?  dictionary.get(key) : key;
	}
	
	//Dil dosyasi da benzer mantikla calistigi icin ayni metot cagrilir
	public String getLanguageDataValue(String key){
		return getSubstitution(key);
	}

	public String getReverseSubstitution(String value) {
		Iterator<Entry<String, String>> it = dictionary.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
			if (pairs.getValue() == value)
				return pairs.getKey();
		}
		return value;
	}
	
	
}
